<?php
include 'functions.php';
//error_reporting(E_ALL);
//http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=Main%20Page

//starting information
$rootTitle = stripslashes($rootTitle);

//parse determiners from title and put them back at the front
//The
if (stripos($rootTitle, ', the')>=1)
{
	$rootTitle = str_ireplace(', the', '', $rootTitle);
	$rootTitle = 'the '.$rootTitle;
}
//An
if (stripos($rootTitle, ', an')>=1)
{
	$rootTitle = str_ireplace(', an', '', $rootTitle);
	$rootTitle = 'an '.$rootTitle;
}
//A
if (stripos($rootTitle, ', a')>=1)
{
	$rootTitle = str_ireplace(', a', '', $rootTitle);
	$rootTitle = 'a '.$rootTitle;
}

//get type
if ($type=='Book')
{
	$searchType = ' (novel)';
}

//convert to url
//capitalize per wikipedia guidelines
$searchTitle = wiki_caps($rootTitle);
//echo $searchTitle;
$searchTitle = urlencode($searchTitle);

//construct url
$rooturl = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles';
$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";

//construct curl request
$request = curl_build($completeurl);
$result = json_decode($request,true);

$missing = $result[query][pages]['-1'][missing];

if (isset($missing))
{
	$missing = 1;
}

//first search is not returning results, rerun with initcaps
if ($missing == 1)
{
	//echo "<br/>No results - rerunning with initcaps<br/>";
	$missing = 0;
	$searchTitle = ucwords($rootTitle);
	$searchTitle = urlencode($searchTitle);
	//construct url
	$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";

	//construct curl request
	$request = curl_build($completeurl);
	$result = json_decode($request,true);

	$missing = $result[query][pages]['-1'][missing];
	if (isset($missing))
	{
		$missing = 1;
	}

}

//if second search is not returning results, try adding media type to search
//e.g. novel, film, album

$pageId = $result[query][pageids][0];//get page id from article info
$result2 = $result[query][pages][$pageId];//get actual article text
$titleP = $result2[title];

$result3 = $result2[revisions][0]['*'];
$results4 = explode('{{', $result3);
$results4 = str_ireplace('}}', '', $results4);

//find infobox
$infoBox = preg_grep('/(?i)Infobox/', $results4);
$infoBox = array_values($infoBox);//reindex
$infoBox = $infoBox[0];//get only first infobox if there are multiples
$infoBoxA[] = $infoBox;//create array
$infoBoxA = array_filter($infoBoxA);//remove empty array elements
$infoBoxA = preg_replace('/\s\s+/', ' ', $infoBoxA);//replace multiple spaces with one

//if second search is not returning results, try adding media type to search
//e.g. novel, film, album
if (is_array($infoBox)&&count($infoBox)==0)//no infobox
{
//convert to url
		//capitalize per wikipedia guidelines
		$searchTitle = wiki_caps($rootTitle);
		$searchTitle .= $searchType;//redo search with type
		$searchTitle = urlencode($searchTitle);
	//construct url
	$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";
	//echo "<a target='_blank' href='$completeurl'>$completeurl</a></br>";

	//construct curl request
$request = curl_build($completeurl);
	$result2 = json_decode($request,true);
	
	$pageId2 = $result2[query][pageids][0];//get page id from article info
	$result22 = $result2[query][pages][$pageId2];//get actual article text
	$titleP2 = $result22[title];

	$result32 = $result22[revisions][0]['*'];
	$results42 = explode('{{', $result32);
	$results42 = str_ireplace('}}', '', $results42);

	$infoBox2 = preg_grep('/(?i)Infobox/', $results42);//match i/I

}

	//find items
	$imageArray = preg_grep('/image/',$infoBoxA);
	$authorPArray = preg_grep('/author =/',$infoBoxA);
	$publisherArray = preg_grep('/publisher/',$infoBoxA);
	$isbnArray = preg_grep('/isbn/', $infoBoxA);
	$pubYearPA = preg_grep('/pub_date/', $infoBoxA);
	$pubYearPB = preg_grep('/published/', $infoBoxA);
	$languageArray = preg_grep('/language/', $infoBoxA);
	$releaseArray = preg_grep('/release_date/', $infoBoxA);

	//find new items
	if (is_array($infoBox2)&&count($infoBox2)>0)
	{
		$infoBox2 = array_values($infoBox2);//reindex
		$infoBox2 = $infoBox2[0];
		$infoBox2A[] = $infoBox2;//create array
		$infoBox2A = preg_replace('/\s\s+/', ' ', $infoBox2A);//replace multiple spaces with one
		$imageArray2 = preg_grep('/image/',$infoBox2A);
		$authorPArray2 = preg_grep('/author.=/',$infoBox2A);
		$authorPArray3 = preg_grep('/author/',$infoBox2A);
		$publisherArray2 = preg_grep('/publisher/',$infoBox2A);
		$isbnArray2 = preg_grep('/isbn/', $infoBox2A);
		$pubYearPC = preg_grep('/pub_date/', $infoBox2A);
		$pubYearPD = preg_grep('/published/', $infoBox2A);
		$languageArray2 = preg_grep('/language/', $infoBox2A);
		$releaseArray2 = preg_grep('/release_date/', $infoBox2A);
	}

//print_r($infoBox);
//echo "<br/><br/><br/>";
//$authorPLink = preg_grep('/authorlink/', $xml3);
//$titleArray = preg_grep('/title/', $xml3);

//extract authors

	if ((is_array($authorPArray)&&count($authorPArray)>0)||(is_array($authorPArray2)&&count($authorPArray2)>0))
	{
		$authorP = array_glue($authorPArray,$authorPArray2,'|','author =');
		$authorP = string_fix($authorP,'author');	
		
	}

if (is_array($authorPLink)&&count($authorPLink)>0)
{
	$authorPLink = array_values($authorPLink);
	$authorPLink = $authorPLink[0];
	$authorPLink = explode('|', $authorPLink);
	$authorPLink = preg_grep('/authorlink/', $authorPLink);

	foreach ($authorPLink as $authorPs)
	{
		//remove everything before = and everything after (
		$authorPPos = strpos($authorPs,'=');

		if ($authorPPos>0)
		{
			$authorPs = substr($authorPs,$authorPPos+1);
		}

		$authorPPos = strpos($authorPs,'(');

		if ($authorPPos>0)
		{
			$authorPs = substr($authorPs,0,$authorPPos);
		}

		$authorPsArray[] = $authorPs;

	}

}

	//extract publication year
	if ((is_array($pubYearPA)&&count($pubYearPA)>0)||(is_array($pubYearPC)&&count($pubYearPC)>0))
	{
		$pubYearP = array_glue($pubYearPA,$pubYearPC,'|','pub_date');
		$pubYearP = string_fix($pubYearP,'in literature');
		$pubYearP = string_fix($pubYearP,'pub_date');
		
		if (strlen($pubYearP)>4)
		{
			$pubYearP = date_fix($pubYearP);//test if its a valid date
		}
	}
	else if ((is_array($pubYearPB)&&count($pubYearPB)>0)||(is_array($pubYearPD)&&count($pubYearPD)>0))
		{
			$pubYearP = array_glue($pubYearPB,$pubYearPD,'|','published');
			$pubYearP = string_fix($pubYearP,'published');
			$pubYearP = string_chop($pubYearP,'(');
			
			if (strlen($pubYearP)>4)
			{
				$pubYearP = date_fix($pubYearP);//test if its a valid date			
			}

		}
	//if the date isn't a year, unset it
	if (is_numeric($pubYearP)===FALSE)
	{
		//echo "Unsetting year<br/>";
		unset($pubYearP);
	}

	//search for a release date if there is no publication year
	if ((is_array($releaseArray)&&count($releaseArray)>0)||(is_array($releaseArray2)&&count($releaseArray2)>0)&&isset($pubYearP)===FALSE)
	{
		$pubYearP = array_glue($releaseArray,$releaseArray2,'|','release_date');
		$pubYearP = string_fix($pubYearP,'release_date');
		$pubYearP = string_fix($pubYearP,'in literature');
		$pubYearP = string_chop($pubYearP,'(');
		
		if (strlen($pubYearP)>4)
		{
			
			$pubYearP = date_fix($pubYearP);//test if its a valid date	
		}
		
				
	}

	//parse title
	if (is_array($titleArray)&&count($titleArray)>0)
	{
		$titleArray = array_values($titleArray);//reindex
		$titleP = $titleArray[0];
		$titleP = string_fix($titleP,'title');
		$titleP = string_fix($titleP,'(disambiguation)');
	}
	else if (isset($titleP))
	{
		$titleP = string_fix($titleP,'(disambiguation)');
		
	}
	else if (isset($titleP2))
	{
		$titleP = string_fix($titleP2,'(disambiguation)');		
	}
	
	

	//parse publishers
	if ((is_array($publisherArray)&&count($publisherArray)>0)||(is_array($publisherArray2)&&count($publisherArray2)>0))
	{
		$pubP = array_glue($publisherArray,$publisherArray2,'|','publisher');
		//if there is both a UK and US publisher, remove the second one
		$pub2 = strpos($pubP, 'UK: [[');
		$pub3 = strpos($pubP, 'US: [[');
		if ($pub3>$pub2)//UK first
		{
		$pubP = substr($pubP, 0, $pub3-1);
		$pubP = str_ireplace('UK:', '', $pubP);
		}
		else if ($pub2>$pub3)//US first
		{
		$pubP = substr($pubP, 0, $pub2-1);
		$pubP = str_ireplace('US:', '', $pubP);
		}
		$pubP = string_fix($pubP,'publisher');
		$pubP = string_fix($pubP,'()');
		//if last character is a comma, remove it
		$pubP = rtrim($pubP, ',');
		$pubP = str_ireplace('(book )', '', $pubP);	

	}

	//parse language
	if((is_array($languageArray)&&count($languageArray)>0)||(is_array($languageArray2)&&count($languageArray2)>0))
	{
		$languageP = array_glue($languageArray,$languageArray2,'|','language');
		$languageP = string_fix($languageP,'language');
	}
	
	//parse ISBN
	if ((is_array($isbnArray)&&count($isbnArray)>0)||(is_array($isbnArray2)&&count($isbnArray2)>0))
	{
		//do we perform ISBN validation here or in the main page?
		$ISBNP = array_glue($isbnArray,$isbnArray2,'|','isbn');
		$ISBNP = string_fix($ISBNP,'isbn',0);//case insensitive search
		$ISBNP = str_ireplace('-', '', $ISBNP);//remove '-'
		$ISBNP = explode(' ',$ISBNP);//if there are multiple ISBNs, get the first one
		$ISBNP = $ISBNP[0];
		$ISBNP = preg_replace('/[^0-9xX]/', '', $ISBNP);//remove any non-digits
		//$ISBNP = preg_replace('/[^0-9].[^xX]*/', '', $ISBNP);
	}

	//parse Image
	if ((is_array($imageArray)&&count($imageArray)>0)||(is_array($imageArray2)&&count($imageArray2)>0))
	{
		$imageSearch = array_glue($imageArray,$imageArray2,'|','image');
		$imageSearch = string_fix($imageSearch,'image');
		$imageSearch = string_fix($imageSearch,'File:');
		$imageSearch = string_fix($imageSearch,'Image:');
		$imageSearch = string_fix($imageSearch,'<!--prefer 1st edition-->');
				
		$imageUrl = str_ireplace(' ','_',$imageSearch);
		//echo $imageUrl."<br/>";
		$imageUrl = 'http://en.wikipedia.org/w/api.php?action=query&titles=Image:'.$imageUrl.'&prop=imageinfo&iiprop=url&format=json&indexpageids&redirects&continue=';
		//echo "<a href='$imageUrl'>$imageUrl</a></br></br>";

		$requestImg = curl_build($imageUrl);
		$resultImg = json_decode($requestImg,true);
		$imgPageId = $resultImg[query][pageids][0];
		$imgUrl = $resultImg[query][pages][$imgPageId][imageinfo][0][url];

	}
/*
if ($missing <> 1)//if page isn't missing
{
	echo "<br/><br/>Wikipedia API values:<br/>";
	echo "Author(s): ".$authorP."<br/>";
	//print_r($authorPsArray);
	echo "Year: ".$pubYearP."<br/>";
	echo "Title: ".$titleP."<br/>";
	echo "Original language: ".$languageP."<br/>";
	echo "Publisher: ".$pubP."<br/>";
	echo "ISBN: ".$ISBNP."<br/>";
	echo "<img src=$imgUrl height=250><br/>";
}
else
{
	echo "Page missing!";
}
*/

?>